// 云函数入口文件
const cloud = require('wx-server-sdk')


cloud.init({
  env:'mupp-5gs2863z7cf6873f'
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  let openid = event.openid
  console.log(openid)
  let res = await db.collection('comment').aggregate()
  .match({       //查询我的笔记
    openid:openid
  })
  .end()
  console.log(res)
  let mynotes = res.list
  mynotes.forEach(v=>{
    if(v.dz.indexOf(openid)>-1){   //判断这个文章是否有点赞
      v.dianzan = 'dianzan.png'
   }else{
    v.dianzan = 'aixin.png'
   }
  })
  mynotes.reverse() 
  let nleftitems = []
  let nrightitems = []
  mynotes.forEach( (item, index)=> {  //分割为两个数组
    if (index % 2) {
      nrightitems.push(item)
    } else {
      nleftitems.push(item)
    }
})


  res = await db.collection('comment').aggregate()
  .match({      //查询我赞过
  dz:openid
  })
  .end()
  console.log(res)
  let mydz = res.list
  mydz.reverse() 
  let zleftitems = []
  let zrightitems = []
  mydz.forEach( (item, index)=> {  //分割为两个数组
    if (index % 2) {
      zrightitems.push(item)
    } else {
      zleftitems.push(item)
    }
})

  res = await db.collection('user').aggregate()
  .match({      //查询我的关注
  follow:openid
  })
  .end()
  console.log(res)
  let myfollow = res.list

  res = await db.collection('user').aggregate()
  .match({      //查询我的粉丝数
    openid:openid
  })
  .end()
  console.log(res)
  let follow = res.list[0].follow.length

  console.log(mynotes,mydz,myfollow)
  return {
    nleftitems,nrightitems,zleftitems,zrightitems,myfollow,follow
  }
}